package com.qf.air.core.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.air.core.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 维多利加
 * @Date: 2021/3/25 19:20
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 前处理
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 从session中查询用户信息
        User user = (User) request.getSession().getAttribute("user");
        if (user!=null){
            return true;
        }

        //获取cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("userCookie".equals(cookie.getName())) {
                    //获取cookie值
                    String key = cookie.getValue();

                    //根据key获取value
                    String value = stringRedisTemplate.opsForValue().get(key);

                    if (!StringUtils.isEmpty(value)) {
                        //反序列化
                        ObjectMapper mapper = new ObjectMapper();
                        User user1 = mapper.readValue(value, User.class);
                        if (user1 != null) {
                            //重置redis中user存活时间
                            stringRedisTemplate.expire(key, 1800, TimeUnit.SECONDS);

                            //将用户信息放入session中
                            request.getSession().setAttribute("user",user1);
                            return true;
                        }
                    }
                }
            }
        }
        response.sendRedirect(request.getContextPath() + "/login.html");
        return false;
    }
}
